import pymysql, json

from common.GetConfig import *

from common.GetConfig import test_host,test_user_db,test_user_host


class ConnMysql(object):
    ip = test_user_host()
    dbName = test_user_db()

    def __init__(self, host=ip, user="root", password="123456", database=dbName):
        try:
            con = pymysql.connect(
                host=host,
                user=user,
                password=password,
                database=database
            )
            self.con = con
            self.cursor = self.con.cursor()
            print('数据库连接成功')
        except Exception as e:
            print("连接失败", e.args)

    def select_tb(self, sql):
        try:
            self.cursor.execute(sql)
            self.con.commit()
            result = self.cursor.fetchall()
            # print('result类型',type(result))    result = cursor.fetchall()类型为元祖
            print("查询到的结果:", json.dumps(result))
            return json.dumps(result)
        except Exception as e:
            print("查询失败", e.args)

    def update_tb(self, sql):
        try:
            self.cursor.execute(sql)
            self.con.commit()
        except Exception as e:
            print("更新失败", e.args)
            self.con.rollback()

    def __del__(self):
        # 这是对象销毁前执行的方法
        self.cursor.close()
        self.con.close()


if __name__ == '__main__':
    sql = 'select id,name from base_worker_info where del_flag=0'
    # print(type(ConnMysql().select_tb(sql)))类型为str
    ConnMysql().select_tb(sql)
